package com.cdc.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.LruCache;
import android.widget.ImageView;

import java.io.File;

/**
 * Created by cdc on 2018/3/28.
 */

public class SimpleImageLoader {
    private static SimpleImageLoader mLoader;
    private LruCache<String,Bitmap> mLrucache;
    public static SimpleImageLoader getInstance(){
        if(mLoader==null){
            synchronized (SimpleImageLoader.class){
                if(mLoader==null){
                    mLoader=new SimpleImageLoader();
                }
            }
        }else{
            return mLoader;
        }
        return mLoader;
    }

    private SimpleImageLoader(){
        int maxSize= (int)Runtime.getRuntime().maxMemory()/8;
        mLrucache=new LruCache<String,Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {

                return value.getByteCount();
            }
        };

    }

    public void displayImage(ImageView view, String url){
        Bitmap bitmap=getBitmapFromCache(url);
        if(bitmap!=null){
            view.setImageBitmap(bitmap);
        }else{
            downLoadImage(view,url);
        }

    }
    private Bitmap getBitmapFromCache(String url){
        return mLrucache.get(url);
    }

    private void putBitmapToCache(Bitmap bitmap,String url){
        if(bitmap!=null){
            mLrucache.put(url,bitmap);
        }
    }

    private void  downLoadImage(final ImageView imageView,final String url){
        ImageTask imageTask=new ImageTask(imageView);
        imageTask.execute(url);
    }

    private class ImageTask extends AsyncTask<String,Void,File>{

        private ImageView imageView;

        private String url;


        public ImageTask(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected File doInBackground(String... strings) {
            url=strings[0];
            DownFile downFile=new DownFile(url);
            return downFile.getImageFile();
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if(file!=null){
                //imageView.getWidth()=0  imageView.getHeight()=0
                Bitmap bitmap= BitmapUtil.ratio(file.getAbsolutePath(),300,300);
                imageView.setImageBitmap(bitmap);
                putBitmapToCache(bitmap,url);

            }

        }
    }

}
